package com.mutouren.web;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mutouren.common.exception.ExceptionUtils;

public class WebUtils {
	
	public static String getActionName(HttpServletRequest request) {
		String result = "";
		String url = request.getRequestURI();
		Pattern p = Pattern.compile("/([\\w_-]+).action");
		Matcher m = p.matcher(url);		
		while(m.find()) {
			if(m.groupCount() == 1) {
				result = m.group(1);
				break;
			}
		}		
		return result;
	}
	
	public static boolean isPost(HttpServletRequest request) {
		return request.getMethod().equals("POST");
	}
	
	public static String successDialog(HttpServletResponse response) {
		try {
			response.getWriter().write("success");
		} catch (Throwable t) {
			throw ExceptionUtils.doUnChecked(t);
		}		
		return null;
	}
	
	public static String failDialog(HttpServletResponse response, String message) {
		try {
			response.getWriter().write(message);
		} catch (Throwable t) {
			throw ExceptionUtils.doUnChecked(t);
		}		
		return null;
	}	
	
	public static String getErrorMessage(List<String> errors) {
		StringBuilder result = new StringBuilder();
		
		for(String error : errors) {
			result.append(String.format("%s \n", error));
		}
		return result.toString();
	}
	
	
	
}